package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/consumer")
public class UserController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    UserService userService;

    @GetMapping("/user")
    public List<User> findUser(){
        return restTemplate.getForObject("http://localhost:8081/provider/user",List.class);
    }

    @GetMapping("/user2")
    public List<User> findUser2(){
        List<ServiceInstance> instances = discoveryClient.getInstances("gec-service-provider");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/provider/user";
        log.info(url);
        return restTemplate.getForObject(url,List.class);
    }

    @GetMapping("/user3")
    public String findUser3(){
        String url = "http://gec-service-provider/provider/user";
        return restTemplate.getForObject(url, List.class).toString();
    }

    @GetMapping("/user4")
    public String findUser4(){
        return userService.findUser().toString();
    }
}
